package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/models"
	"encoding/json"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"time"
)

type NotificationController struct {
	BaseController
}

func (this *NotificationController) Prepare() {
	this.BaseController.Prepare()
}

func (this *NotificationController) Index() {
	this.checkLogin()
	this.Data["pageTitle"] = "通知列表"
	this.ActiveSidebarUrl()
	this.Data["canEdit"] = this.checkActionAuthor(this.controllerName, "Edit")
	this.setTpl()
}

func (this *NotificationController) DataGrid() {
	var params models.NotificationQueryParam
	json.Unmarshal(this.Ctx.Input.RequestBody, &params)

	data, total := models.NotificationPageList(&params)
	this.BootstrapJson(total, data)
}

func (this *NotificationController) Edit() {
	if this.Ctx.Request.Method == "POST" {
		this.Save()
	}
	Id, _ := this.GetInt(":id", 0)
	m := &models.Notification{}
	var err error
	if Id > 0 {
		m, err = models.NotificationOne(Id)
		if err != nil {
			this.pageError("数据无效，请刷新后重试")
		}
	}
	this.Data["m"] = m
	this.setTpl("notification/edit", "shared/layout_pullbox")
}

func (this *NotificationController) Save() {
	m := models.Notification{}
	o := orm.NewOrm()
	var err error
	if err = this.ParseForm(&m); err != nil {
		this.jsonResult(enums.JRCodeFailed, "获取数据失败"+err.Error(), m.Id)
	}
	valid := validation.Validation{}
	b, err := valid.Valid(&m)
	if err != nil {
		this.jsonResult(enums.JRCodeFailed, err.Error(), m.Id)
	}
	//校验不通过
	if !b {
		for _, err := range valid.Errors {
			this.jsonResult(enums.JRCodeFailed, err.Key+":"+err.Message, m.Id)
		}
	}

	if m.Id == 0 {
		m.CreateAt = time.Now().Unix()
		if _, err := o.Insert(&m); err != nil {
			this.jsonResult(enums.JRCodeFailed, "添加失败"+err.Error(), m.Id)
		}
	} else {
		oM, err := models.NotificationOne(m.Id)
		if err != nil {
			this.jsonResult(enums.JRCodeFailed, "", m.Id)
		} else {
			m.CreateAt = oM.CreateAt
			m.SendTime = oM.SendTime
			m.CancelTime = oM.CancelTime
			m.DeleteTime = oM.DeleteTime
			if _, err := o.Update(&m); err != nil {
				this.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
			}
		}
	}
	this.jsonResult(enums.JRCodeSuccess, "保存成功", m.Id)
}

func (this *NotificationController) Delete() {
	this.checkAuthor()
	Id, _ := this.GetInt("id", 0)
	if Id == 0 {
		this.jsonResult(enums.JRCodeFailed, "选择数据无效", 0)
	}
	deleted := models.NotificationDelete(Id)
	if deleted {
		this.jsonResult(enums.JRCodeSuccess, "删除成功", Id)
	} else {
		this.jsonResult(enums.JRCodeFailed, "删除失败", Id)
	}
}
